<style lang="less">
    @import './style.less';
</style>
<template>
    <div class="user">
        <div class="op-header">
            <el-button
                    class="add"
                    size="small"
                    type="info"
                    @click="add">
                <i class="el-icon-circle-plus icon-right" />创建任务
            </el-button>
            <div class="search">
                <el-cascader
                        class="enable-select"
                        :clearable="true"
                        v-model="enableValue"
                        :options="enableOptions"
                        :props="cascaderProps"
                        placeholder="启用状态" />
                <el-input
                        class="search-input "
                        size="small"
                        v-model="searchInput"
                        placeholder="请输入查询关键字"
                        prefix-icon="el-icon-search" />
                <el-button
                        class="search-button"
                        size="small"
                        type="primary"
                        @click="search">
                    <i class="el-icon-search icon-right" />查询
                </el-button>
            </div>
        </div>
        <table-ex
                :rows="trainList.content"
                :total="trainList.total"
                :columns="columns"
                :options="options"
                :on-option="onClickOption"
                :on-operation="onClickOperation"
                :on-page-change="onPageChange" />
        <dialog-ex
                v-if="dialogModal"
                :title="this.dialogModal === 'add' ? '新增任务' : '编辑任务'"
                :form="form"
                :mode="dialogModal"
                :search-data="learnList"
                :init="currentRole"
                :remote-method="onQueryChange"
                :popup-focus="popupFocus"
                :popup-value="releaseObjc" />
        <multistage
                v-if="multistageModal"
                title="选择对象"
                :data="deparList"
                :default-props="multistageProps"
                :table-columns="multistageColumns"
                :table-rows="traineeList"
                row-key="userId"
                :init-data="traineeIds"
                :modal-confirm="multistageConfirm"
                :modal-cancel="multistageCancel"
                :tree-node-click="(row, path) => multistageNodeClick(row, path)" />
    </div>
</template>

<script>
    import { mapActions, mapGetters, mapMutations } from 'vuex'
    import { Base64 } from 'js-base64'
    import pageConfig from './config'
    import api from '@/api'

    import tableEx from '@/components/table/tableEx'
    import dialogEx from '@/components/dialog/dialogEx'
    import multistage from '@/components/custom/multistage'

    export default {
        name: 'trainTask',
        components: {
            'table-ex': tableEx,
            'dialog-ex': dialogEx,
            'multistage': multistage
        },
        data() {
            return {
                searchInput: '',
                enableValue: [],
                departmentValue: '',
                dialogModal: '',
                multistageModal: false,
                columns: pageConfig.columns,
                options: pageConfig.options,
                enableOptions: pageConfig.enableOptions,
                multistageProps: pageConfig.multistageProps,
                multistageColumns: pageConfig.multistageColumns,
                releaseObjc: '',
                traineeIds: [],
                learnIds: [],
                cascaderProps: {
                    value: 'id',
                    label: 'name',
                    children: 'subClasses'
                },
                currentRole: {},
                form: {
                    items: pageConfig.addTrainFormItems,
                    default: { enabled: true, taskNature: '必修' },
                    actions: {
                        cancel: () => {
                            this.dialogModal = ''
                        },
                        confirm: (data, mode) => {
                            if (!data.name) {
                                this.$Message({
                                    type: 'warning',
                                    center: true,
                                    message: '请填写任务名称'
                                })
                                return
                            }
                            this.learnIds = data.learnIds
                            console.log('after data', data)
                            if (mode === 'add') {
                                this.addTrain({
                                    data,
                                    cb: (res) => {
                                        this.traineeRelation(res)
                                        this.learnRelation(res)
                                    }
                                })
                            }
                            if (mode === 'edit') {
                                this.traineeRelation(this.currentRole)
                                this.learnRelation(this.currentRole)
                                this.editTrain(data)
                            }
                            this.dialogModal = ''
                        },
                    }
                }
            }
        },
        computed: {
            ...mapGetters([
                'trainList',
                'learnList',
                'deparList',
                'traineeList'
            ])
        },

        created() {
            this.loadInitData()
        },

        mounted() {
        },

        methods: {

            ...mapActions([
                'addTrain',
                'editTrain',
                'getTrainList',
                'getLearnList',
                'getDeparList',
                'getTraineeList',
                'addLearnRelation',
                'addTrineeRelation',
                'removeonedatatrain'
            ]),

            ...mapMutations([
                'setTrainList',
                'SETATASKPAGE',
                'SETTRAINEELIST'
            ]),

            loadInitData() {
                this.getTrainList()
                this.getLearnList()
                this.getDeparList()
            },

            add() {
                this.releaseObjc = ''
                this.traineeIds = []
                this.dialogModal = 'add'
            },

            search() {
                const filter = {
                    name: this.searchInput,
                    enabled: !!this.enableValue ? this.enableValue[0] : null
                }
                this.SETATASKPAGE({
                    number: 1,
                    pages: 0,
                    filter
                })
                this.getTrainList()
            },

            onQueryChange(query) {
                let data = {
                    size: 0,
                    number: 0,
                    total: 0,
                    pages: 0,
                    filter: {
                        name: query
                    }
                }
                this.getLearnList(data)
            },

            popupFocus(e) {
                this.$store.commit('SETTRAINEELIST', [])
                this.multistageModal = true
            },

            multistageConfirm(results) {
                this.multistageModal = false
                this.$store.commit('SETTRAINEELIST', [])
                this.traineeIds = []
                let traineeIds = []
                let templets = []
                if (results) {
                    this.traineeIds = results
                    this.releaseObjc = `已选${this.traineeIds.length}人`

                }
            },

            multistageCancel(e) {
                this.$store.commit('SETTRAINEELIST', [])
                this.multistageModal = false
            },

            multistageNodeClick(row) {
                const data = {
                    size: 0,
                    number: 0,
                    total: 0,
                    pages: 0,
                    filter: {
                        enabled: true,
                        orgIds: [
                            row.id
                        ]
                    }
                }
                this.getTraineeList(data)
            },

            traineeRelation(objc) {
                if (this.traineeIds) {
                    let params = {
                        id: objc.id,
                        action: 'replace',
                        lIds: this.traineeIds
                    }
                    this.addTrineeRelation(params)
                }
            },

            learnRelation(objc) {
                if (this.learnIds && this.learnIds.length) {
                    let params = {
                        id: objc.id,
                        action: 'replace',
                        lIds: this.learnIds
                    }
                    this.addLearnRelation(params)
                }
            },

            batchOption() {
            },

            onClickOption(option, rows) {
                this.releaseObjc = ''
                const prop = option;
                switch (prop) {
                    case 'batchdelete': {
                        if (rows && rows.length) {
                            let id = rows.map(item => {
                                return item.id
                            })
                            this.removeonedatatrain(
                                id
                            )
                        }
                        break
                    }
                    case 'batchrefresh': {
                        this.loadInitData()
                        break
                    }
                    default: {
                    }
                }
            },

            onClickOperation(oper, row) {
                let self = this
                let id = row.id
                const prop = oper.prop
                switch (prop) {
                    case 'preview': {
                        console.log('onClickOperation >> ', oper, row)
                        api.getTrainDetail({ id: row.id }, {
                            success: (training) => {
                                console.log('onClickOperation >> ', oper, training)
                                self.$router.push({
                                    name: 'courseBusiness',
                                    query: {
                                        course: Base64.encode(
                                            JSON.stringify({
                                                trainingId: row.id,
                                                businessId: training.learningTasks[0].businessTemplates[0].id,
                                                learningId: training.learningTasks[0].id,
                                                mode: 'study',
                                                action: 'preview'
                                            })
                                        )
                                    }
                                })
                                self.$store.commit('course/update', { businessTemplates: training.learningTasks[0].businessTemplates })

                            }
                        })

                        break
                    }
                    case 'delete': {
                        this.removeonedatatrain(
                            [id]
                        )
                        break
                    }
                    case 'edit': {
                        api.getTrainDetail({ id: row.id }, {
                            success: (res) => {
                                if (res.learningTasks && res.learningTasks.length) {
                                    let learnIds = res.learningTasks.map(item => {
                                        return item.id
                                    })
                                    res['learnIds'] = learnIds
                                }
                                if (res.employees && res.employees.length) {
                                    let traineeIds = res.employees.map(item => {
                                        return item.id
                                    })
                                    let traineeNames = res.employees.map(item => {
                                        return item.name
                                    })
                                    this.releaseObjc = `已选${traineeNames.length}人`
                                    this.traineeIds = traineeIds
                                    res['traineeIds'] = traineeIds
                                }
                                this.currentRole = res
                                this.dialogModal = 'edit'
                            }
                        })
                        break
                    }
                    default: {
                    }
                }
            },

            onPageChange(number) {
                this.SETATASKPAGE({ number });
                this.getTrainList()
            }
        }
    }
</script>
